
import {
  loginChecked,
  updateUserInfo
} from '@/api/user.js'
import router from '@/router'

const user = {
  namespaced: true,
  state: {
    isExpand: true,
    isLogin: true,
    userInfo: null,
    router: ['index'],

    accessToken: null,
    refreshToken: null,
    storageKeys: {
      accessToken: 'accessToken',
      refreshToken: 'refreshToken'
    }
  },
  mutations: {
    // 设置是否展开
    SET_EXPAND: (state, flag) => {
      state.isExpand = !flag
    },
    // 设置路由
    SET_ROUTER: (state, name) => {
      state.router = name
    },
    loadTokensFromLocalStorage: (state) => {
      state.accessToken = localStorage.getItem(state.storageKeys.accessToken)
      state.refreshToken = localStorage.getItem(state.storageKeys.refreshToken)
    },
    clearTokens: (state) => {
      state.accessToken = null
      state.refreshToken = null
      localStorage.removeItem(state.storageKeys.accessToken)
      localStorage.removeItem(state.storageKeys.refreshToken)
    },
    // 登录设置用户信息
    SET_USER_INFO: (state, data) => {
      state.userInfo = data
      state.accessToken = data[0].accessToken
      state.refreshToken = data[0].refreshToken
      localStorage.setItem(state.storageKeys.accessToken, data[0].accessToken)
      localStorage.setItem(state.storageKeys.refreshToken, data[0].refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(data))
    },
    // 设置用户信息
    GET_USER_INFO: (state, data) => {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      if (token) {
        if (userInfo) {
          state.userInfo = JSON.parse(userInfo)[0]
        } else {
          state.userInfo = data
        }
      }
    }
  },
  actions: {
    // 登录
    LOGIN_CHECK_METHOD ({ commit, state }, params) {
      return new Promise((resolve, reject) => {
        loginChecked(params).then(res => {
          if (res.data.code === '1') {
            commit('SET_USER_INFO', res.data.result)
            router.push('/')
          }
          resolve()
        })
      })
    },
    // 更新个人信息
    UPDATE_USER_METHOD ({ dispatch, commit, state }, params) {
      return new Promise((resolve, reject) => {
        updateUserInfo(params).then(res => {
          if (res.data.code === '1') {
            dispatch('LOGIN_CHECK_METHOD', params)
          } else {

          }
          resolve()
        })
      })
    }
  }
}

export default user
